package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

public class OrderDAO {
    // 保存订单
    public void saveOrder(Order order) throws Exception {
        try (Connection connection = DatabaseConnection.getConnection()) {
            // 保存订单信息到 Orders 表
            String orderQuery = "INSERT INTO Orders (CustomerName, StoreID, OrderTime, TotalPrice, OrderStatus) VALUES (?, ?, NOW(), ?, ?)";
            PreparedStatement orderStatement = connection.prepareStatement(orderQuery, Statement.RETURN_GENERATED_KEYS);
            orderStatement.setString(1, order.getCustomerName());
            orderStatement.setInt(2, order.getStoreID());
            orderStatement.setDouble(3, order.getTotalCost()); // 使用动态计算的总金额
            orderStatement.setString(4, "Pending");
            orderStatement.executeUpdate();


            // 获取生成的订单ID
            var generatedKeys = orderStatement.getGeneratedKeys();
            int orderID = -1;
            if (generatedKeys.next()) {
                orderID = generatedKeys.getInt(1);
            }

            // 保存订单详情到 OrderDetails 表
            String detailQuery = "INSERT INTO OrderDetails (OrderID, ItemID, Quantity) VALUES (?, ?, ?)";
            PreparedStatement detailStatement = connection.prepareStatement(detailQuery);

            for (OrderDetail detail : order.getOrderDetails()) {
                detailStatement.setInt(1, orderID);
                detailStatement.setInt(2, detail.getItem().getItemID());
                detailStatement.setInt(3, detail.getQuantity());
                detailStatement.addBatch(); // 批量处理
            }
            detailStatement.executeBatch();
        }
    }
}
